package repositories

import (
	"context"
	"github.com/pkg/errors"
	"go.didapinche.com/foundation/plat-echo/app/ops/models"
	"gorm.io/gorm"
)

type AccessRecordRepository interface {
	Create(ctx context.Context, record *models.AccessRecord) error
	FindByUID(ctx context.Context, UID string, keyword string, graphType models.AccessGraphType, page int, size int) ([]*models.AccessRecord, int64, error)
}

type accessRecordRepository struct {
	db *gorm.DB
}

func NewAccessRecordRepository(db *gorm.DB) AccessRecordRepository {
	return &accessRecordRepository{
		db: db,
	}
}

func (a *accessRecordRepository) Create(ctx context.Context, record *models.AccessRecord) error {
	if err := a.db.WithContext(ctx).Table(models.AccessRecordTableName).Create(record).Error; err != nil {
		return errors.Wrap(err, "create AccessRecord error")
	}
	return nil
}

func (a *accessRecordRepository) FindByUID(ctx context.Context, UID string, keyword string, graphType models.AccessGraphType, page int, size int) (result []*models.AccessRecord, total int64, err error) {
	db := a.db.WithContext(ctx).Table(models.AccessRecordTableName).Where("uid = ? and name != ''", UID)
	if keyword != "" {
		db = db.Where("name like ?", "%"+keyword+"%")
	}
	if graphType != "" {
		db = db.Where("graph_type = ?", graphType)
	}
	db = db.Group("name")
	if err = db.Count(&total).Error; err != nil {
		return result, 0, errors.Wrap(err, "count FindByUID error")
	}
	if err := db.Order("id desc").Offset((page - 1) * size).Limit(size).Find(&result).Error; err != nil {
		return result, 0, errors.Wrap(err, "FindByUID error")
	}
	return result, total, nil
}
